package com.example.springbott.wx_service;

import com.example.springbott.bean.*;
import com.example.springbott.bean.kerbal.WxCartCheckoutVo;
import com.example.springbott.bean.kerbal.WxCartIndexVo;
import com.example.springbott.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.example.springbott.util.Count.MALL_SYSTEM_EXPRESS_FREIGHT_MIN;
import static com.example.springbott.util.Count.MALL_SYSTEM_EXPRESS_FREIGHT_VALUE;

@Component
public class WxCartServiceImpl implements WxCartService {
    @Autowired
    MarketCartMapper marketCartMapper;
    @Autowired
    MarketGoodsMapper marketGoodsMapper;
    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;
    @Autowired
    MarketAddressMapper marketAddressMapper;
    @Autowired
    MarketCouponMapper marketCouponMapper;
    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;
    @Autowired
    MarketSystemMapper marketSystemMapper;

    @Override
    public Integer wxCartGoodscount(Integer id) {
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        if (id == null) {
            return 0;
        }
        criteria.andUserIdEqualTo(id);
        return (int) marketCartMapper.countByExample(marketCartExample);
    }


    @Override
    @Transactional
    public Integer wxCartFastAdd(Integer id, Integer goodsId, Integer number, Integer productId) {
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andUserIdEqualTo(id);
        criteria.andDeletedEqualTo(false);
        criteria.andProductIdEqualTo(productId);
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);
        if (marketCarts.size()==0){
            MarketCart marketCart = new MarketCart();
            //userid
          marketCart.setUserId(id);
          //goods
          marketCart.setGoodsId(goodsId);
          MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(goodsId);
          marketCart.setGoodsName(marketGoods.getName());
          marketCart.setGoodsSn(marketGoods.getGoodsSn());
          //productId
          MarketGoodsProduct marketGoodsProduct = marketGoodsProductMapper.selectByPrimaryKey(productId);
          marketCart.setProductId(productId);
          marketCart.setPrice(marketGoodsProduct.getPrice());
          marketCart.setSpecifications(marketGoodsProduct.getSpecifications()[0]);
          marketCart.setPicUrl(marketGoodsProduct.getUrl());
          //number
          marketCart.setNumber(number.shortValue());
          marketCart.setChecked(false);
          //time
          marketCart.setAddTime(new Date());
          marketCart.setUpdateTime(new Date());
          marketCart.setDeleted(false);
          marketCart.setChecked(true);
          marketCartMapper.insert(marketCart);
          return marketCart.getId();
      }else {
          MarketCart marketCart = marketCarts.get(0);
          Short oldNumber = marketCart.getNumber();
          marketCartMapper.updateByKerb(goodsId,oldNumber+number,productId,id);
            return marketCart.getId();
        }




    }


    @Override
    public WxCartIndexVo wxCartIndex(Integer id) {
        WxCartIndexVo wxCartIndexVo = new WxCartIndexVo();
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        criteria.andUserIdEqualTo(id);
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);
        wxCartIndexVo.setCartList(marketCarts);

        WxCartIndexVo.CartTotalDTO cartTotalDTO = new WxCartIndexVo.CartTotalDTO();
        cartTotalDTO.setGoodsCount(marketCarts.size());


        int checkedCount = 0;
        int totalPrice = 0;
        int checkedPrice = 0;

        for (int i = 0; i < marketCarts.size(); i++) {
            MarketCart marketCart = marketCarts.get(i);
            totalPrice += marketCart.getNumber() * marketCart.getPrice().intValue();
            if (marketCart.getChecked()) {
                checkedCount++;
                checkedPrice += marketCart.getNumber() * marketCart.getPrice().intValue();
            }
        }
        cartTotalDTO.setCheckedGoodsCount(checkedCount);
        cartTotalDTO.setCheckedGoodsAmount(checkedPrice);
        cartTotalDTO.setGoodsAmount(totalPrice);
        cartTotalDTO.setGoodsCount(marketCarts.size());
        wxCartIndexVo.setCartTotal(cartTotalDTO);

        return wxCartIndexVo;
    }


    @Override
    @Transactional
    public Integer wxCartChecked(ArrayList<Integer> productIds, Integer isChecked, Integer id) {
        try {
            for (int i = 0; i < productIds.size(); i++) {
                marketCartMapper.updateCheckStatus(productIds.get(i), isChecked, id);
            }
        } catch (Exception e) {
            return 500;
        }

        return 0;


    }

    @Override
    @Transactional
    public Integer wxCartUpdate(Integer goodsId, Integer number, Integer productId, Integer id) {

        return marketCartMapper.updateByKerb(goodsId, number, productId, id);

    }


    @Override
    public Integer wxCartDelete(ArrayList<Integer> list, Integer id) {

        int total = 0;
        for (int i = 0; i < list.size(); i++) {
            total += marketCartMapper.DeleteByKerb(list.get(i), id);
        }
        return total;


    }


    @Override
    public WxCartCheckoutVo wxCartCheckout(Integer cartId, Integer addressId, Integer couponId, Integer userCouponId, Integer grouponRulesId, Integer id) {
      if (cartId==0){
          WxCartCheckoutVo wxCartCheckoutVo = new WxCartCheckoutVo();
          MarketCartExample marketCartExample = new MarketCartExample();
          MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
          criteria.andDeletedEqualTo(false);
          criteria.andUserIdEqualTo(id);
          criteria.andCheckedEqualTo(true);
          List<MarketCart> marketCartListTotal = marketCartMapper.selectByExample(marketCartExample);

//          wxCartCheckoutVo.setCheckedGoodsList(marketCartbase );
//          List<MarketCart> marketCartListTotal=new ArrayList<>();
//          for (int i = 0; i < marketCartbase.size(); i++) {
//           Integer cartIds = marketCartbase.get(i).getId().intValue();
//              MarketCartExample.Criteria criteriaCart = marketCartExample.createCriteria();
//              criteriaCart.andDeletedEqualTo(false);
//              criteriaCart.andIdEqualTo(cartIds);
//              criteriaCart.andCheckedEqualTo(true);
//              List<MarketCart> marketCartList = marketCartMapper.selectByExample(marketCartExample);
//              marketCartListTotal.addAll(marketCartList);
//          }



          //grouponID
          wxCartCheckoutVo.setGrouponPrice(0);
          wxCartCheckoutVo.setGrouponRulesId(0);
          //goodsTotalPrice 原价
          int goodsTotalPrice = 0;
          for (int i = 0; i < marketCartListTotal.size(); i++) {
              goodsTotalPrice += marketCartListTotal.get(i).getPrice().intValue() * marketCartListTotal.get(i).getNumber().intValue();
          }
          //cartID
          wxCartCheckoutVo.setCartId(cartId);
          //couponId
          if (couponId!=-1){
              wxCartCheckoutVo.setCouponId(couponId);
          }else {
              int bestConponId=-1;
              int bestDiscount=0;
              MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
              MarketCouponUserExample.Criteria marketCouponUserExampleCriteria = marketCouponUserExample.createCriteria();
              marketCouponUserExampleCriteria.andDeletedEqualTo(false);
              marketCouponUserExampleCriteria.andUserIdEqualTo(id);
              marketCouponUserExampleCriteria.andStartTimeLessThan(new Date());
              marketCouponUserExampleCriteria.andEndTimeGreaterThan(new Date());
              marketCouponUserExampleCriteria.andStatusEqualTo((short)0);
              List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(marketCouponUserExample);
              for (int i = 0; i < marketCouponUsers.size(); i++) {
                  MarketCouponUser marketCouponUser = marketCouponUsers.get(i);
                  MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(marketCouponUser.getCouponId());
                  if (goodsTotalPrice>marketCoupon.getMin().intValue()&&marketCoupon.getDiscount().intValue()>bestDiscount){
                      bestDiscount=marketCoupon.getDiscount().intValue();
                      bestConponId=marketCoupon.getId();
                  }
              }
              couponId=bestConponId;
              wxCartCheckoutVo.setCouponId(couponId);
          }
          //addressId
          wxCartCheckoutVo.setAddressId(addressId);
          //gruoponPrice 0
          wxCartCheckoutVo.setGrouponPrice(0);
          //checkedAddress 查询地址的详细信息
          MarketAddress marketAddress = marketAddressMapper.selectByPrimaryKey(addressId);
          wxCartCheckoutVo.setCheckedAddress(marketAddress);


          //availablecouponlength
          MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
          MarketCouponUserExample.Criteria criteria1 = marketCouponUserExample.createCriteria();
          criteria1.andDeletedEqualTo(false);
          criteria1.andUserIdEqualTo(id);
          List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(marketCouponUserExample);
          wxCartCheckoutVo.setAvailableCouponLength(marketCouponUsers.size());
          //orderTotalPrice

          //actualPrice
          //freightprice 运费 默认一直为0
          //couponPrice 优惠卷面值
          MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(couponId);
          int marketCouponValue=0;
          if (marketCoupon!=null){
              wxCartCheckoutVo.setCouponPrice(marketCoupon.getDiscount().intValue());
              marketCouponValue=marketCoupon.getDiscount().intValue();
          }else {
              wxCartCheckoutVo.setCouponPrice(0);
          }

          String minFreightFree = marketSystemMapper.selectKeyValueByKeyName(MALL_SYSTEM_EXPRESS_FREIGHT_MIN);
          if (goodsTotalPrice>Integer.parseInt(minFreightFree)){
              wxCartCheckoutVo.setFreightPrice(0);
              wxCartCheckoutVo.setActualPrice(goodsTotalPrice-marketCouponValue);
          }else {
              String freight = marketSystemMapper.selectKeyValueByKeyName(MALL_SYSTEM_EXPRESS_FREIGHT_VALUE);
              wxCartCheckoutVo.setFreightPrice(Integer.parseInt(marketSystemMapper.selectKeyValueByKeyName(MALL_SYSTEM_EXPRESS_FREIGHT_VALUE)));
              wxCartCheckoutVo.setActualPrice(goodsTotalPrice-marketCouponValue+Integer.parseInt(freight));
          }
          MarketCouponUser marketCouponUser = marketCouponUserMapper.selectByPrimaryKey(userCouponId);
          wxCartCheckoutVo.setGoodsTotalPrice(goodsTotalPrice);
          wxCartCheckoutVo.setUserCouponId(userCouponId);


          if (marketCouponUser!=null){
              wxCartCheckoutVo.setOrderTotalPrice(goodsTotalPrice-marketCouponValue);
              return wxCartCheckoutVo;
          }else {
              wxCartCheckoutVo.setOrderTotalPrice(goodsTotalPrice);
              return wxCartCheckoutVo;
          }

      }//前面是cartid为0的情况
        WxCartCheckoutVo wxCartCheckoutVo = new WxCartCheckoutVo();
        //checkedGoodsList 匹配userid，checked
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        criteria.andIdEqualTo(cartId);
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);
        wxCartCheckoutVo.setCheckedGoodsList(marketCarts);
        //grouponID
        wxCartCheckoutVo.setGrouponPrice(0);
        wxCartCheckoutVo.setGrouponRulesId(0);
        //goodsTotalPrice 原价
        int goodsTotalPrice = 0;
        for (int i = 0; i < marketCarts.size(); i++) {
            goodsTotalPrice += marketCarts.get(i).getPrice().intValue() * marketCarts.get(i).getNumber().intValue();
        }
        //cartID

        wxCartCheckoutVo.setCartId(cartId);
        //CouponId
        if (couponId!=-1){
            wxCartCheckoutVo.setCouponId(couponId);
        }else {
            int bestConponId=-1;
            int bestDiscount=0;
            MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
            MarketCouponUserExample.Criteria marketCouponUserExampleCriteria = marketCouponUserExample.createCriteria();
            marketCouponUserExampleCriteria.andDeletedEqualTo(false);
            marketCouponUserExampleCriteria.andUserIdEqualTo(id);
            marketCouponUserExampleCriteria.andStartTimeLessThan(new Date());
            marketCouponUserExampleCriteria.andEndTimeGreaterThan(new Date());
            marketCouponUserExampleCriteria.andStatusEqualTo((short)0);
            List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(marketCouponUserExample);
            for (int i = 0; i < marketCouponUsers.size(); i++) {
                MarketCouponUser marketCouponUser = marketCouponUsers.get(i);
                MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(marketCouponUser.getCouponId());
                if (goodsTotalPrice>marketCoupon.getMin().intValue()&&marketCoupon.getDiscount().intValue()>bestDiscount){
                    bestDiscount=marketCoupon.getDiscount().intValue();
                    bestConponId=marketCoupon.getId();
                }
            }
            couponId=bestConponId;
            wxCartCheckoutVo.setCouponId(couponId);
        }

        //addressId
        wxCartCheckoutVo.setAddressId(addressId);
        //gruoponPrice 0
        wxCartCheckoutVo.setGrouponPrice(0);
        //checkedAddress 查询地址的详细信息
        MarketAddress marketAddress = marketAddressMapper.selectByPrimaryKey(addressId);
        wxCartCheckoutVo.setCheckedAddress(marketAddress);


        //availablecouponlength
        MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
        MarketCouponUserExample.Criteria criteria1 = marketCouponUserExample.createCriteria();
        criteria1.andDeletedEqualTo(false);
        criteria1.andUserIdEqualTo(id);
        List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(marketCouponUserExample);
        wxCartCheckoutVo.setAvailableCouponLength(marketCouponUsers.size());
        //orderTotalPrice

        //actualPrice
        //freightprice 运费 默认一直为0
        //couponPrice 优惠卷面值
        MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(couponId);
        int marketCouponValue=0;
        if (marketCoupon!=null){
            wxCartCheckoutVo.setCouponPrice(marketCoupon.getDiscount().intValue());
            marketCouponValue=marketCoupon.getDiscount().intValue();
        }else {
            wxCartCheckoutVo.setCouponPrice(0);
        }

        String minFreightFree = marketSystemMapper.selectKeyValueByKeyName(MALL_SYSTEM_EXPRESS_FREIGHT_MIN);
        if (goodsTotalPrice>Integer.parseInt(minFreightFree)){
            wxCartCheckoutVo.setFreightPrice(0);
            wxCartCheckoutVo.setActualPrice(goodsTotalPrice-marketCouponValue);
        }else {
            String freight = marketSystemMapper.selectKeyValueByKeyName(MALL_SYSTEM_EXPRESS_FREIGHT_VALUE);
            wxCartCheckoutVo.setFreightPrice(Integer.parseInt(marketSystemMapper.selectKeyValueByKeyName(MALL_SYSTEM_EXPRESS_FREIGHT_VALUE)));
            wxCartCheckoutVo.setActualPrice(goodsTotalPrice-marketCouponValue+Integer.parseInt(freight));
        }
        MarketCouponUser marketCouponUser = marketCouponUserMapper.selectByPrimaryKey(userCouponId);
        wxCartCheckoutVo.setGoodsTotalPrice(goodsTotalPrice);
        wxCartCheckoutVo.setUserCouponId(userCouponId);


        if (marketCouponUser!=null){
            wxCartCheckoutVo.setOrderTotalPrice(goodsTotalPrice-marketCouponValue);
            return wxCartCheckoutVo;
        }else {
            wxCartCheckoutVo.setOrderTotalPrice(goodsTotalPrice);
            return wxCartCheckoutVo;
        }








    }


}
